import sys
from PyQt5 import QtCore,  QtWidgets
from PyQt5.QtCore import Qt
import PyQt5
from ui_ffbh import Ui_Form
import copy
import logging
import myglobal
import pymssql
use_ejff_filt=True
class Model(QtCore.QAbstractTableModel):
    """
    表格数据模型MVC模式
    """
 
    def __init__(self, data):
        super().__init__()
        # self._raw=None
        self._data = data
        self.headers=["方法编号","方法","二级方法","二级分析技术"]
    def filterData(self,filt):
        if use_ejff_filt:
            return myglobal.server.getffbh_filt(filt,myglobal.mainw.db.getejff())
        else:
            return myglobal.server.getffbh_filt(filt,[])
    def myfilter(self,filt):
        self.updateData(self.filterData(filt))
    def data_at_row(self,row):
        return self._data[row]#[0]#self.updateData(self.filterData(filt))        
    def updateData(self, data):
        """
        (自定义)更新数据
        """
        self.beginResetModel()
        self._data = data
        self.endResetModel()
 
    def data(self, index, role=None):
        if role == Qt.DisplayRole:
            # logging.info([len(self._data),index.row()])
            value = self._data[index.row()][index.column()]
            return value
        if role == Qt.DecorationRole:
            pass
    def rowCount(self, parent=None, *args, **kwargs):
        """
        行数
        """
        return len(self._data)
    def columnCount(self, parent=None, *args, **kwargs):
        """
        列数
        """
        return len(self.headers)
    def headerData(self, section, orientation, role=Qt.DisplayRole):
        """
        标题定义
        """
        if role != Qt.DisplayRole:
            return None
        if orientation == Qt.Horizontal:
            return self.headers[section]
        return int(section + 1)

class DlgFfbh(QtWidgets.QDialog):
    ui = Ui_Form()
    def __init__(self, parent=None):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui.setupUi(self)
        try:
            self.model = Model(myglobal.server.getffbh_filt("",myglobal.mainw.db.getejff()))
        except pymssql.OperationalError as e:
            QtWidgets.QMessageBox.information(None,"",str(e))
            pass
        self.ui.todoView.setModel(self.model)
        self.ui.btn_ok.clicked.connect(self.ok)
        self.ui.btn_cancel.clicked.connect(self.cancel)
        self.ui.todoView.setSelectionBehavior(PyQt5.QtWidgets.QAbstractItemView.SelectRows)
        self.ui.todoView.setColumnWidth(0, 200)
        self.ui.todoView.setColumnWidth(1, 400)
        self.ui.todoView.setColumnWidth(2, 150)
        self.ui.todoView.setColumnWidth(3, 200)
        self.ui.todoView.doubleClicked.connect(self.double_click_table_view_item)
        self.ui.lineEdit_query.returnPressed.connect(self.query)
        self.ui.pushButton_query.clicked.connect(self.query)
        self.ui.checkBox.stateChanged.connect(self.ejff_change)
        self.select_row=None
    def ejff_change(self,c):
        global use_ejff_filt
        use_ejff_filt=self.ui.checkBox.isChecked()
    # def editingFinished_triger(self):
    #     # logging.info(self.sender().isModified())
    #     if not self.sender().isModified(): 
    #         # logging.info("return")
    #         return
    #     self.sender().setModified(False)
    #     self.query()
    def query(self):
        logging.info(self.sender())
        self.model.myfilter(self.ui.lineEdit_query.text())
    def double_click_table_view_item(self,qModelIndex):
        self.select_row=self.model.data_at_row(qModelIndex.row())
        self.accept()
    def ok(self):
        indexes = self.ui.todoView.selectedIndexes()
        if indexes:
            # Indexes is a list of a single item in single-select mode.
            index = indexes[0]
            row=index.row()
            self.select_row=self.model.data_at_row(row)
            self.accept()

    def cancel(self):
        self.reject()

    def add(self):
        """
        Add an item to our todo list, getting the text from the QLineEdit .todoEdit
        and then clearing it.
        """
        text = self.ui.todoEdit.text()
        # if text:  # Don't add empty strings.
        # Access the list via the model.
        self.model.todos.append(text)
        # Trigger refresh.        
        self.model.layoutChanged.emit()
        #  Empty the input
        self.ui.todoEdit.setText("")
        self.save()

    def delete(self):
        indexes = self.ui.todoView.selectedIndexes()
        if indexes:
            # Indexes is a list of a single item in single-select mode.
            index = indexes[0]
            # Remove the item and refresh.
            del self.model.todos[index.row()]
            self.model.layoutChanged.emit()
            # Clear the selection (as it is no longer valid).
            self.ui.todoView.clearSelection()
            self.save()

    def save(self):
        pass


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = DlgArr([])
    window.show()
    app.exec()
